package services.security;

import models.*;
import models.pubobj.AniObjectState;
import models.user.*;
import play.Logger;
import services.exception.*;
import utils.*;

public class AniSecurityService{

	//req id
	public static Long generateReqId(){
		return SecureUtils.generateTimeMillis();
	}
	//session id utils
	public static Long generateUniqueId(){
		return SecureUtils.generateRandomUniqueId();
	}
	//object state existence
	public static AniObjectState getObjectStateWithKey(String stateKey){
		AniObjectState oneObjectState = AniObjectState.findByStateKey(stateKey.trim());
		if(oneObjectState == null){
			throw new AniAuthException("STATE_NOT_EXISTS");
		}
		return oneObjectState;
	}
	
	//reqId legality
	public static void checkReqIdLegality(Long reqId) {
		if(!isReqIdLegal(reqId)){
            Logger.error("ILLEGAL REQID = " + reqId);
            throw new AniAuthException("REQID_ILLEGAL");
		}
	}
	private static boolean isReqIdLegal(Long reqId){
		boolean result = true;
		result = AniPatternUtils.isReqIdFormatLegal(reqId);
		result = isReqIdTimestampLegal(reqId);
		return result;
	}
	
	private static boolean isReqIdTimestampLegal(Long reqId){
		Long curTime = System.currentTimeMillis();
		if(
				(curTime - reqId) > SecureUtils.secureTimeoutMills
				|| (curTime - reqId) < 0
		){
			return false;
		}
		return true;
	}
	//email existence
	public static AniUser getUserInfoWithEmail(String email) {
		AniUser oneUser =  AniUser.findByEmail(email.trim());
		if(oneUser == null){
			throw new AniAuthException("USER_NOT_FOUND");
		}
		return oneUser;
	}
}
